package com.openatc.agent.controller;


import com.google.gson.JsonObject;
import com.openatc.agent.model.User;
import com.openatc.agent.service.MessageService;
import com.openatc.agent.utils.HttpUtil;
import com.openatc.agent.utils.TokenUtil;
import com.openatc.comm.common.CommClient;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.RESTRetUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

import static com.openatc.comm.common.CommunicationType.COMM_SOCKET_TYPE_UDP;
import static com.openatc.comm.common.CommunicationType.EXANGE_TYPE_CENTER;


@RestController
@CrossOrigin
public class ThirdPlatMessageController {

    private Logger logger = Logger.getLogger(ThirdPlatMessageController.class.toString());

    //    @Autowired
    private CommClient commClient = new CommClient();

    @Value("${agent.thirdplat.ip}")
    private String adapterIP;

    @Value("${agent.thirdplat.port}")
    private Integer adapterPort;

    private String protocolType = "scp";

//    @Autowired
//    MessageController messageController;
    @Autowired
    private MessageService messageService;


    @PostMapping(value = "/centeradapter/custom")
    public RESTRet postDevsMessage(HttpServletRequest httpServletRequest, @RequestBody JsonObject jsonObject) {
        MessageData responceData = null;
        MessageData requestData = null;
        try {
            //当收到第三方的post请求时，直接将该请求发送给centeradapter python脚本
            requestData = new MessageData();
            requestData.setInfotype("control/pattern");
            requestData.setOperation("set-request");
            requestData.setData(jsonObject);
            String agentid = jsonObject.get("data").getAsJsonObject().get("name").getAsString();
            requestData.setAgentid(agentid);
            requestData.setModel("thirdparty");

            responceData = commClient
                    .exange(adapterIP, adapterPort, protocolType, EXANGE_TYPE_CENTER, requestData,COMM_SOCKET_TYPE_UDP);

            // 把设置请求set-request的操作保存到历史记录中
            String OperatorIp = null;
            if (httpServletRequest == null) {
                OperatorIp = "localhost";
            } else {
                OperatorIp = HttpUtil.getIpAddress(httpServletRequest);
            }

            // 记录操作记录
            if (requestData.getOperation().equals("set-request")) {
//                String token = null;
//                User subject = null;
//                if (httpServletRequest != null) {
//                    token = httpServletRequest.getHeader("Authorization");
//                    if (token != null) {
//                        subject = (User) SecurityUtils.getSubject().getPrincipal();
//                    }
//                }
                String userName = TokenUtil.getCurrentUserName();
                messageService.CreateHisParam(requestData, RESTRetUtils.successObj(responceData), OperatorIp, userName);
            }

        } catch (Exception e) {
            logger.warning("Request /centeradapter/custom Error:" + e.getMessage() + " Data:" + requestData);
        }

        return RESTRetUtils.successObj(responceData);
    }

}
